package com.liao.badminton.code.util;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.liao.badminton.dto.SystemUsersDto;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.Map;

public class NettyUtil {
    static Logger logger = LoggerFactory.getLogger(NettyUtil.class);
    public static Map<String, ChannelHandlerContext> sendMap = MapUtil.newConcurrentHashMap();
    //    public static Map<String, String> clientIpKeyMap = MapUtil.newConcurrentHashMap();
    static Logger log = LoggerFactory.getLogger(NettyUtil.class);

    public static String toBind(ChannelHandlerContext ctx) {
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = ipSocket.getAddress().getHostAddress();
        int port = ipSocket.getPort();
        return clientIp + port;
    }

    /***缓存客户端*/
    public static void addClientCache(ChannelHandlerContext ctx) {
        String inIP = toBind(ctx);
        if (NettyUtil.sendMap.containsKey(inIP)) {
//            String s = toBind(NettyUtil.sendMap.get(key));
//            if (!s.equals(inIP)) {
////                NettyUtil.clientIpKeyMap.remove(s);
//                NettyUtil.addSendMap(inIP, ctx);
////                NettyUtil.clientIpKeyMap.put(inIP, key);
//            }
        } else {
            NettyUtil.addSendMap(inIP, ctx);
//            if (!clientIpKeyMap.containsKey(inIP)) {
//                NettyUtil.clientIpKeyMap.put(inIP, key);
//            }
        }
        log.info("客户端增加缓存成功,:{}", JSON.toJSONString(sendMap));
    }

    /**
     * 指定客户端发送消息
     */
    public static Boolean sendByKey(String key, SystemUsersDto userInfo) {
        if (sendMap.containsKey(key)) {
            ChannelHandlerContext channelHandlerContext = sendMap.get(key);
            channelHandlerContext.write(userInfo);
            channelHandlerContext.flush();
            return true;
        }
        return false;
    }

    /**
     * 所有客户端发送消息
     */
    public static Boolean sendAll(SystemUsersDto userInfo) {
        for (Map.Entry<String, ChannelHandlerContext> stringChannelHandlerContextEntry : NettyUtil.sendMap.entrySet()) {
            stringChannelHandlerContextEntry.getValue().writeAndFlush(userInfo);
            return true;
        }
        return false;
    }

    public static void addSendMap(String key, ChannelHandlerContext ctx) {
//        if (sendMap.containsKey(key)) {
//            logger.info("复盖客户端：设备id:{},原地址：{},新地址：{}",key,toBind(NettyUtil.sendMap.get(key)),ctx.channel().remoteAddress());
//        } else {
//            logger.info("新增客户端：设备id:{},地址：{}", key,ctx.channel().remoteAddress());
//        }
        sendMap.put(key, ctx);
    }

    public static void clear(ChannelHandlerContext ctx) {
        logger.info("移除客户端：{}", ctx.channel().remoteAddress());
        String offIp = NettyUtil.toBind(ctx);
//        String key = clientIpKeyMap.get(offIp);
        sendMap.remove(offIp);
//        clientIpKeyMap.remove(offIp);
        log.info("在连接客户端：{}", JSON.toJSONString(sendMap));
    }
}
